package online.chenke.juc;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 多个线程做累加
 */
public class Test003 {
	public static void main(String[] args) throws InterruptedException {
		singleThread();
		multiThread();
	}
	
	public static void singleThread() {
		int num = 1_0000_0000;
		int sum = 0;
		long now = System.currentTimeMillis();
		for (int i = 1; i <= num; i++) {
			sum+=i;
		}
		System.out.println("time:"+(System.currentTimeMillis()-now)+"ms sum:"+sum);
		
	}
	
	public static void multiThread() throws InterruptedException {
		int num = 1_0000_0000;
		AtomicInteger sum = new AtomicInteger();
		long now = System.currentTimeMillis();
		int threadNum = 3;
		int remainder = num % threadNum;
		CountDownLatch latch = new CountDownLatch(threadNum);
		
		for (int i = 1; i <= threadNum; i++) {
			final int finalIndex = i;
			
			new Thread(()->{
				int segSum = 0;
				int segNum = num/threadNum;
				
				if(threadNum==finalIndex) {
					for (int j = (finalIndex-1)*segNum+1; j <= finalIndex*segNum+remainder; j++) {
						segSum+=j;
					}
				}else {
					for (int j = (finalIndex-1)*segNum+1; j <= finalIndex*segNum; j++) {
						segSum+=j;
					}
				}
				
				sum.addAndGet(segSum);
				latch.countDown();
			}, "t"+i).start();
		}
		
		latch.await();
		System.out.println("time:"+(System.currentTimeMillis()-now)+"ms sum:"+sum.get());
	}
}
